import { createApp } from 'vue'
import router from './router'
import store from './store'
import ElementPlus from 'element-plus'
import 'element-plus/lib/theme-chalk/index.css'
import { axiosInstance } from './axiosDefaults'
import axios from 'axios'
import App from './App.vue'

const token = store.state.token
axios.defaults.baseURL = 'http://apis.imooc.com/api/'
axios.defaults.headers.common.Authorization = `Bearer ${token}`

axiosInstance.interceptors.request.use(config => {
  // 打开loading
  store.commit('fetchErr', { isErr: false, message: '' }) // 先设置成false
  store.commit('fetchLoading', true)

  return config
})
axios.interceptors.request.use(config => {
  if (config.data instanceof FormData) {
    config.data.append('icode', '38CD209A8A08B4B6')
  } else {
    config.data = { ...config.data, icode: '38CD209A8A08B4B6' }
  }
  config.params = { icode: '38CD209A8A08B4B6' }
  return config
})
axiosInstance.interceptors.response.use(config => {
  // 关闭loading
  store.commit('fetchLoading', false)
  return config
}, e => {
  // 响应拦截器处理错误方法
  const { error } = e.response.data
  // 改变错误信息状态，提示错误
  store.commit('fetchErr', { isErr: true, message: error }) // 设置成true 打开提示
  // 关闭loading
  store.commit('fetchLoading', false)
  return Promise.reject(error)
})
const app = createApp(App)
app.use(ElementPlus)
app.use(store)
app.use(router)
app.mount('#app')
